package client;
import java.awt.event.*;
import java.net.*;
import java .io.*;
import java.math.BigInteger;
/**
 * SettlersClient
 * @author: Keith Wyss
 *
 */

public class SettlersClient implements ActionListener {
    /* Declaring necessary objects to read and configure server
     * and read and write to/from the server
     */
    protected client.gui.ConnectionWindow IPwindow;
    private ObjectInputStream in;
    private PrintWriter myWriter;
    private boolean talkready = false;
    public SettlersClient() {
      IPwindow = new client.gui.ConnectionWindow(this, new javax.swing.JFrame(), true);
    /*
     * Get information from child gui about what server and port to access.
     */
    }

    public void initGameBoard(){
        /*
         * This should involve reading game state from the server and
         * constructing a suitable board
         */
        client.gui.GameWindow clientwindow = new client.gui.GameWindow();
    }
    public void actionPerformed(ActionEvent e)
    {
        boolean shutwindow = true;

        /*
         * Code for if the action is connect button
         */
        if (e.getSource() == IPwindow.getButton()){
        Integer temp = new Integer(0);
        int Port = temp.parseInt(IPwindow.getPort());
        /*
         * Socket constructor takes strange objects.
         * That's why so many transformations occur.
         */
        BigInteger IP = new BigInteger(IPwindow.getIP());
        byte[] rawIP = IP.toByteArray();
        InetAddress addr = null;
        try{
            addr = InetAddress.getByAddress(rawIP);
        }
        catch(UnknownHostException b){
            System.out.println("Unable to find IP address given.");
            shutwindow = false;
        }
        try{
                Socket connection = new Socket(addr, Port);
         in =
             new ObjectInputStream(
                     connection.getInputStream());


         myWriter =
             new PrintWriter(
                 new BufferedWriter(
                     new OutputStreamWriter(connection.getOutputStream())), true);
        }
        catch(Exception a){
            System.out.println("Unable to connect to server.");
            shutwindow = false;
            }

        /*
         * Gui for connection should close once it's established.
         */
        if (shutwindow){
            IPwindow.hide();
            IPwindow = null;
            talkready = true;
            initGameBoard();
        }


        /*
         * More methods to come for the interactions with the game board Gui
         * components
         */
      }


    }
           public Object ReadObject(){
            Object object = null;
               try {object  = in.readObject();}
               catch(Exception exc){}
           return object;
        }
           public String ReadString(){
               return (String) ReadObject();
           }

}


